//
//  MyIndexView.m
//  梁家伟
//
//  Created by 梁家伟 on 17/2/23.
//  Copyright © 2017年 itcast. All rights reserved.
//

#import "MyIndexView.h"

@implementation MyIndexView{
    NSMutableArray<UIButton*>* _btnList;
    NSArray<NSString*>* _btnName;
    UIButton* _selectedBtn;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(instancetype)initWithData:(NSArray<NSString*>*)categories{
    
    if(self = [super init]){
        _btnName = categories;
        _maxCount = categories.count;
        [self setupUI];
    }
    return self;
}


-(void)setIndex:(NSUInteger)index{
    _index = index;
    
    UIButton* btn = _btnList[index];
    
    [self changeSelectedBtn:btn];
}


-(void)setupUI{
    
    _btnList = [NSMutableArray array];
    
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width / _btnName.count;
    
    [_btnName enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        UIButton* btn = [UIButton cz_textButton:_btnName[idx] fontSize:16 normalColor:[UIColor blackColor] selectedColor:PPColor];
        btn.backgroundColor = [UIColor whiteColor];
        btn.tag = idx;
        
        [self addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(width);
            make.height.equalTo(self);
            make.centerY.equalTo(self);
            make.left.mas_equalTo(idx * width);
        }];
        
        [btn addTarget:self action:@selector(indexSelected:) forControlEvents:UIControlEventTouchUpInside];
        [_btnList addObject:btn];
    }];
    
    _selectedBtn = _btnList.firstObject;
    _btnList.firstObject.selected = YES;
}

//按钮被点击后通知控制发送事件
-(void)indexSelected:(UIButton*)btn{
    [self changeSelectedBtn:btn];
    self.tag = btn.tag;
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

//切换选择的按钮
-(void)changeSelectedBtn:(UIButton*)btn{
    _selectedBtn.selected = NO;
    btn.selected = YES;
    _selectedBtn = btn;
}


@end
